package com.xiyuan.smartutils.domain.date;

import com.xiyuan.smartutils.DateTimes;

import java.util.Date;

import static com.xiyuan.smartutils.DateTimes.YYYY_MM_DD_HH_MM_SS;

/**
 * 日期时间段
 *
 * @author xiyuan-lgz 2025-08-02 @version v1.0.0 新建与整理
 */
public class DateRange {
    private Date start;
    private Date end;
    
    private transient String format = YYYY_MM_DD_HH_MM_SS;
    
    public DateRange() {}
    
    public DateRange(Date start, Date end) {
        if(start != null && end != null){
            if(start.after(end)){
                Date temp = start;
                start = end;
                end = temp;
            }
        }
        this.start = start;
        this.end = end;
    }
    
    public Date getStart() {
        return start;
    }
    
    public DateRange setStart(Date start) {
        this.start = start;
        return this;
    }
    
    public Date getEnd() {
        return end;
    }
    
    public DateRange setEnd(Date end) {
        this.end = end;
        return this;
    }
    
    public boolean isRange() {
        return start != null && end != null;
    }
    
    public long getStartTime() {
        return start == null ? 0 : start.getTime();
    }
    
    public long getEndTime() {
        return end == null ? 0 : end.getTime();
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        try {
            sb.append(start == null ? null : "\"" + DateTimes.getFormatter(format).format(start.toInstant()) + "\"");
            sb.append(", ");
            sb.append(end == null ? null : "\"" + DateTimes.getFormatter(format).format(end.toInstant()) + "\"");
        }
        catch (Exception e) {
            sb.setLength(1);
            sb.append(start == null ? null : "\"" + DateTimes.getFormatter(YYYY_MM_DD_HH_MM_SS).format(start.toInstant()) + "\"");
            sb.append(", ");
            sb.append(end == null ? null : "\"" + DateTimes.getFormatter(YYYY_MM_DD_HH_MM_SS).format(end.toInstant()) + "\"");
        }
      
        sb.append("]");
        return sb.toString();
    }
    
    public String getFormat() {
        return format;
    }
    
    public DateRange setFormat(String format) {
        this.format = format;
        return this;
    }
}
